
import $ from "jquery";

let info = {}

class SearchBar {
	constructor(options) {
		this.editor = options.editor
    this.el = options.el
		this.init()
  }

  init() {
    let me = this
    if(!me.editor.graph){
      return
    }
    me.graph = me.editor.graph

    me.$input = me.el.find('input')

    me.$input.on("keydown", evt => {
      if (evt.keyCode == 27 && $(this).val()) {
        me.clear();
        $(this).val('')
        return;
      }
      if (evt.keyCode == 13) {
        me.doSearch(evt.shiftKey);
      }
    })

    me.$button = me.el.find('button')
    me.$button.on('click', evt => {
      me.doSearch();
    })
  }

  clear () {
    info.searchInfo = null;
  } 

  doSearch (prov) {
    let me = this
    let value = me.$input.val();
    if (!value) {
      me.clear();
      return;
    }

    if (!info.searchInfo || info.searchInfo.value != value) {
      let result = me.search(value, info);
      if (!result || !result.length) {
        me.clear();
        return;
      }
      info.searchInfo = { value: value, result: result };
    }
    this.doNext(prov);
  }

  doNext (prov) {
    let me =  this
    if (
      !info.searchInfo ||
      !info.searchInfo.result ||
      !info.searchInfo.result.length
    ) {
      return;
    }
    let searchInfo = info.searchInfo;
    let result = info.searchInfo.result;
    if (result.length == 1) {
      me.select(result[0], 0);
      return;
    }
    if (searchInfo.index === undefined) {
      searchInfo.index = 0;
    } else {
      searchInfo.index += prov ? -1 : 1;
      if (searchInfo.index < 0) {
        searchInfo.index += result.length;
      }
      searchInfo.index %= result.length;
    }
    if (me.select(result[searchInfo.index], searchInfo.index) === false) {
      info.searchInfo = null;
      me.doSearch();
    }
  }

  search (name) {
    let result = [];
    let reg = new RegExp(name, "i");
    let graph = this.graph;
    graph.forEach(function(e) {
      if (graph.isVisible(e) && e.name && reg.test(e.name)) {
        result.push(e.id);
      }
    });
    return result;
  }

  select (item) {
    let graph = this.graph
    item = graph.graphModel.getById(item);
    if (!item) {
      return false;
    }
    graph.setSelection(item);
    graph.sendToTop(item);
    var bounds = graph.getUIBounds(item);
    if (bounds) {
      graph.centerTo(bounds.cx, bounds.cy, Math.max(2, graph.scale), true);
    }
  }
}

export default SearchBar
